<?php

/**
 * 代理层级模型
 * Class Agent
 */
namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

Class Agent extends BaseModel
{

    protected $table = "agent";

    /**
     * @param $where
     * 获取管理员信息
     */
    public function getOne($where, $fileds = '*')
    {
        return $this->_getOne($where, $fileds);
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     *插入数据
     */
    public function add($data)
    {
        return $this->_add($data);
    }


    /***
     * @param array $id
     * @param array $data
     * 更新数据
     */
    public function up($where, $data)
    {
        return $this->_updata($where, $data);
    }

    /**
     * @param $id
     * 删除数据
     */
    public function del($id)
    {
        return $this->_del(['id' => $id]);
    }

    public function del2(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *
     */
    public function getFxData($condition)
    {
        $order['id'] = "desc";
        $rows = $this->getList($condition, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        return $rows;
    }

    public function getLevOneAgentList($bid)
    {
        $agents = $this->select('agent.id as aid')
            ->leftJoin('agent_lev', 'agent.lev', '=', 'agent_lev.id')
            ->where('agent.bid', $bid)
            ->where('agent_lev.lev', 1)
            ->get();
        return $agents;
    }

    public function getDingjiAgentList($bid)
    {
        $where['bid'] = $bid;
        $where['pid'] = 0;
        $agents = $this->getList($where);
        return $agents;
    }

    /**
     * 获取所有代理层级信息
     * 并分页显示
     */
    public function getAgentList($request)
    {
        //dd($request);
        $where = [];
        //待审核,已审核
        if ($request['status']) {
            $where['status'] = ['in', [1, 2]];
        } else {
            $where['status'] = 0;
        }

        $where['bid'] = session('adminId');

        //搜索by zxj20170720
        if ($request['keywords']) {
            if (is_numeric($request['keywords'])) {
                $where['mobile'] = $request['keywords'];
            } else {
                $where['agent_name'] = ['like', '%' . $request['keywords'] . '%'];
            }
        }

        if ($lev = $request['lev']) {
            $where['lev'] = $lev;
        }

//        if($province_id = $request['province_id']){
//            $where['province_id'] = $province_id;
//        }
//        if($city_id = $request['city_id']){
//            $where['city_id'] = $city_id;
//        }
//        if($area_id = $request['area_id']){
//            $where['area_id'] = $area_id;
//        }

        /*$lev = $request['lev'];
        $tel = $request['mobile'];
        if ($lev) {
            $where['lev'] = $lev;
        }
        if ($tel) {
            $where['mobile'] = $tel;
        }*/
        $order['id'] = "desc";
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        return $rows;
    }

    /**
     * 获取代理详情
     */
    public function getAgentDetais($request)
    {
        $id = $request['id'];
        if (empty($id)) {
            $res = ['status' => 0, 'msg' => '参数为空'];
            return $res;
        }
        $where['id'] = $id;
        $data = $this->getOne($where);
        if (empty($data)) {
            $res = ['status' => 0, 'msg' => "未查到数据"];
            return $res;
        }
    }

    // 获取代理人信息
    public function getAgentInfo($id)
    {
        $where['id'] = $id;
        $data = $this->getOne($where);
        $data = $data->toArray();
        return $res = ['status' => 1, 'msg' => 'ok', 'data' => $data];
    }

    /**
     * 添加代理员信息
     */
    public function addAgent($request)
    {

        $agent_name = trim($request['agent_name']);
        $wx = trim($request['wx']);
        $tel = trim($request['mobile']);
        $password = trim($request['password']);
        $cpassword = trim($request['cpassword']);
        $lev = trim($request['lev']);
        $area_ = trim($request['area']);


        if (empty($lev) || empty($agent_name) || empty($password) || empty($area_) || empty($tel)) {
            $res = ['status' => 0, 'msg' => "代理员信息填写不完整"];
            return $res;
        }

        if ($password != $cpassword) {
            return ['status' => 0, 'msg' => "两次密码不一致"];
        }
        $agent = $this->getOne(['mobile' => $tel]);
        if ($agent) {
            return ['status' => 0, 'msg' => "该手机号已被注册，请重新填写"];
        }
        $data['agent_name'] = $agent_name;
        $data['wx'] = $wx;
        $data['mobile'] = $tel;
        $data['password'] = Md5($password);
        $data['lev'] = $lev;
        $data['area'] = $area_;
        $data['bid'] = session('adminId');
        $data['created_at'] = date("Y-m-d H:i:s", time());
        $data['updated_at'] = date("Y-m-d H:i:s", time());
        $result = $this->_add($data);
        if ($result) {
            $res = ['status' => 1, 'msg' => "代理员信息添加成功"];
            return $res;
        }
        $res = ['status' => 0, 'msg' => "代理员信息添加失败"];
        return $res;
    }

    /**
     * 添加代理员信息
     */
    public function addAgentFrom($request)
    {
        $inviter = $this->getOne(['id' => $request['pid']]);
        if (!$inviter) {
            return ['status' => 0, 'msg' => "非法操作"];
        }
        $password = "123456";
        $lev = trim($request['lev']);
        $agent_name = trim($request['agent_name']);
        $area_ = trim($request['area']);
        $tel = trim($request['tel']);
        $wx = trim($request['wx']);
        $idcard = trim($request['idcard']);
        $bank_name = trim($request['bank_name']);
        $bank_num = trim($request['bankno']);
        if (empty($lev) || empty($agent_name) || empty($password) || empty($area_) || empty($tel) || empty($wx) || empty($idcard)) {
            return ['status' => 0, 'msg' => "代理员信息填写不完整"];
        }
        $agent = $this->getOne(['mobile' => $tel]);
        if ($agent) {
            return ['status' => 0, 'msg' => "该手机号已被注册，请重新填写"];
        }
        $data['password'] = Md5($password);
        $data['lev'] = $lev;
        $data['agent_name'] = $agent_name;
        $data['mobile'] = $tel;
        $data['area'] = $area_;
        $data['wx'] = $wx;
        $data['idcard'] = $idcard;
//        $data['bank_name'] = $bank_name;
//        $data['bank_no'] = $bank_num;
        $data['pid'] = $request['pid'];
        $data['bid'] = $inviter['bid'];
        $data['created_at'] = date('Y-m-d H:i:s', time());
        $data['updated_at'] = date('Y-m-d H:i:s', time());
        $resulte = $this->add($data);
        if ($resulte) {
            return ['status' => 200, 'msg' => "代理员信息添加成功"];
        }
        return ['status' => 0, 'msg' => "代理员信息添加失败"];
    }

    /**
     * 登录
     * @param $request 参数
     * @return array
     */
    public function homeLogin($request)
    {

        $account = $request['mobile'];
        $password = $request['password'];
        //dd($account);
        if (empty($account) || empty($password)) {
            $res = ['status' => 0, 'msg' => "登录信息不能为空"];
            return $res;
        }

        $where['mobile'] = $account;
        $where['password'] = MD5($password);
        $Agent = new Agent();
        $resulte = $Agent->getOne($where);
        //dd($resulte);
        if (!$resulte) {
            $res = ['status' => 0, 'msg' => "用户不存在"];
            return $res;
        }
        if ($resulte['status'] == 0) {
            $res = ['status' => 0, 'msg' => "正在审核中"];
            return $res;
        }
        if ($resulte['status'] == 2) {
            $res = ['status' => 0, 'msg' => "审核不通过"];
            return $res;
        }
        // 生成token
        session(['agent' => ['aid' => $resulte['id'], 'name' => $resulte['agent_name'], 'wx' => $resulte['wx'], 'bid' => $resulte['bid'], 'pid' => $resulte['pid']]]);
        $res = ['status' => 1, 'msg' => "登录成功", 'data' => array('aid' => $resulte['id'], 'name' => $resulte['agent_name'])];
        return $res;
    }

    public function editBank($request)
    {
        $where['id'] = session('agent')['aid'];
        if (!$request['oldpwd']) {
            return '请输入原始密码！';
        }
        if (!$request['password']) {
            return '请输入新密码！';
        }
        if (!$request['repwd']) {
            return '请输入确认密码！';
        }
        $agent = $this->getOne($where);
        if ($agent['password'] != md5($request['oldpwd'])) {
            return '原始密码错误！';
        }
        if ($request['pwd'] && $request['repwd']) {
            if ($request['pwd'] != $request['repwd']) {
                return '两次密码不一致！';
            }
            $data['password'] = md5($request['pwd']);
        }
//        $data['bank_name'] = $request['bank_name'];
//        $data['bank_no'] = $request['bank_no'];
        $res = $this->up($where, $data);
        if (!$res) {
            return '操作失败！';
        }
        return '操作成功！';
    }

    public function AgentUpload($request)
    {
        $pics = $request['pics'];
        if (empty($pics)) {
            $res = ['status' => 0, 'msg' => '图片不能为空'];
            return $res;
        }
        $imgPath = upImgs($pics, 'proxypic/');
        $data['proxy'] = $imgPath;
        $aid = session('adminId');
        $admin = new Admin();
        $where['id'] = $aid;
        $res = $admin->up($where, $data);
        if (!$res) {
            $res = ['status' => 0, 'msg' => "授权证书上传失败"];
            return $res;
        }
        $res = ['status' => 1, 'msg' => '图片上传成功'];
        return $res;
    }

    public function AgentUploadTo($request)
    {
        $aid = session('adminId');
        //dd($request['img']);
        $path = '';
        if ($request['img']) {

            $base64_url = $_POST['img'];

            $base64_body = substr(strstr($base64_url, ','), 1);

            $pics = base64_decode($base64_body);

            $path = 'upload/brand/' . $aid . '.png';

            $data['proxy'] = $path;

            //$admin = new Admin();
            $brand = new Brand();
            //dd($aid);
            $where['id'] = $aid;
            $res = $brand->up($where, $data);
            if (!$res) {
                return ['status' => 0, 'msg' => "品牌代理书上传失败"];
            }

            if (file_put_contents($path, $pics)) {

                return ['status' => 1, 'msg' => '品牌代理书上传成功', 'data' => $path];

            } else {

                return ['status' => 0, 'msg' => '品牌代理书上传失败', 'data' => $path];

            }


        }

        return ['status' => 1, 'msg' => '图片上传失败', 'data' => $path];


        //$res = $this->agent->AgentUploadTo(request());
        // return ajax_return($res);

//
//        $pics = $request['pics'];
//        if(empty($pics)){
//            $res = ['status'=>0,'msg'=>'图片不能为空'];
//            return $res;
//        }
//        $imgPath = upImgs($pics,'agent/'.session('admin')['aid']);
//        $res = ['status'=>1,'msg'=>'图片上传成功','data'=>$imgPath];
//        return $res;
    }

    public function checkAgent($request)
    {
        $field = 'mobile';
        $res = $this->getOne([$field => $request['code']]);
        if (!$res) {
            $field = 'wx';
            $res = $this->getOne([$field => $request['code']]);
            if (!$res) {
                return '您查询的代理商不存在';
            }
        }
        return '您查询的代理商存在！';
    }

    public function getLogout()
    {
        Session::forget('agent');
    }

    public function getAgentLevRateById($aid, $bid)
    {
        $agent = $this->getOne(['id' => $aid]);
//        $bid = $agent['bid'];
//        $id = $agent['lev'];
//        if (strstr($agent['bid'],',')) {
//            $bids = explode(',',$agent['bid']);
//            array_pop($bids);
//            array_shift($bids);
//        }
//        if (strstr($agent['lev'],',')) {
//            $levs = explode(',',$agent['lev']);
//            array_pop($levs);
//            array_shift($levs);
//        }
//        $index = 0;
//        if (is_array($bids)) {
//            foreach ($bids as $k=>$v) {
//                if ($bid == $v) {
//                    $index = $k;
//                }
//            }
//            if (is_array($levs)) {
//                $id = $levs[$index];
//            }
//        }

        $agentLev = new Agentlev();
        return $agentLev->getAgentLev(['bid' => $bid, 'lev' => $agent['lev']]);
    }

    //修改代理状态
    public function verify($request)
    {
        $where['id'] = $request['id'];
        $res = $this->up($where, ['status' => $request['status']]);
        $ajaxData['status'] = $res ? 1 : 0;
        $ajaxData['msg'] = '操作成功！';
        if (!$res) {
            $ajaxData['msg'] = '操作失败！';
        }
        return $ajaxData;
    }


    //ajax删除代理商
    public function deleteOneAgent($request)
    {

        $where['id'] = $request['id'];

        $res = $this->del2($where);
        if (!$res) {
            $data['status'] = 0;
            $data['msg'] = '删除代理成员失败！';
            return $data;
        }

        $data['status'] = 1;
        $data['msg'] = '删除代理成员成功！';
        return $data;

    }


}
